﻿using InTheHand.Net.Bluetooth;
using InTheHand.Net;
using InTheHand.Net.Sockets;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace DataManageSystem.Controllers
{
    /// <summary>
    /// 蓝牙通讯模块
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class BluetoothController : ControllerBase
    {
        /// <summary>
        /// 扫描附近的蓝牙设备
        /// </summary>
        [HttpGet("scan")]
        public IActionResult ScanDevices()
        {
            List<string> devices = new();
            BluetoothClient bluetoothClient = new();
            var nearbyDevices = bluetoothClient.DiscoverDevices();

            foreach (var device in nearbyDevices)
            {
                devices.Add($"{device.DeviceName} ({device.DeviceAddress})");
            }

            return Ok(devices);
        }

        [HttpPost("send")]
        public async Task<IActionResult> SendData([FromBody] BluetoothMessage message)
        {
            try
            {
                BluetoothAddress address = BluetoothAddress.Parse(message.DeviceAddress);
                BluetoothEndPoint endpoint = new(address, BluetoothService.SerialPort);
                BluetoothClient client = new();
                client.Connect(endpoint);

                using var stream = client.GetStream();
                byte[] data = System.Text.Encoding.UTF8.GetBytes(message.Data);
                await stream.WriteAsync(data, 0, data.Length);
                client.Close();

                return Ok("数据发送成功");
            }
            catch (Exception ex)
            {
                return BadRequest($"发送失败: {ex.Message}");
            }
        }

        public class BluetoothMessage
        {
            public string DeviceAddress { get; set; }
            public string Data { get; set; }
        }

    }
}
